﻿using HandyControl.Data;
using HandyControl.Tools;
using HandyControl.Tools.Extension;
using HandyControlDemo.Model;
using HandyControlDemo.ViewModel;
using System;
using System.ComponentModel;
using System.IO;
using System.IO.Pipes;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;

namespace HandyControlDemo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow
    {
        private MainWindowViewModel vm;
        private int ThemeColorFlag = 0;

        public MainWindow()
        {
            InitializeComponent();
            InitialResourceDictionary();
            vm = new MainWindowViewModel();
            DataContext = vm;
            App.StartListening(WakeApp);//多开时顶置主页面
                                        //Tasking();

        }
        public async void Tasking()
        {
            using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(10));
            while (await timer.WaitForNextTickAsync())
            {
                WaitData();
            }
        }
        private static void WaitData()
        {

            using (NamedPipeServerStream pipeServer =
            new NamedPipeServerStream("testpipe", PipeDirection.InOut, 1))
            {
                try
                {
                    pipeServer.WaitForConnection();
                    pipeServer.ReadMode = PipeTransmissionMode.Byte;
                    using (StreamReader sr = new StreamReader(pipeServer))
                    {
                        string con = sr.ReadToEnd();
                        Console.WriteLine(con);
                    }
                }
                catch (IOException e)
                {
                    throw e;
                }
            }
        }

        void WakeApp()
        {
            Dispatcher.Invoke(() =>
            {
                if (WindowState == WindowState.Minimized)
                {
                    WindowState = WindowState.Normal;
                }

                Activate();
            });
        }
        // Ititial ResourceDictionary
        private void InitialResourceDictionary()
        {
            // Theme
            ResourceDictionary theme = new ResourceDictionary
            {
                Source = new Uri("pack://application:,,,/Resource/Style/Theme/BaseLight.xaml")
            };
            Resources.MergedDictionaries.Add(theme);
            // Color
            ResourceDictionary color = new ResourceDictionary
            {
                Source = new Uri("pack://application:,,,/Resource/Style/Primary/Primary.xaml")
            };
            Resources.MergedDictionaries.Add(color);
            // Language
            ResourceDictionary lang = new ResourceDictionary
            {
                Source = new Uri("pack://application:,,,/Resource/Lang/Lang.zh-CN.xaml")
            };
            Resources.MergedDictionaries.Add(lang);
        }

        // Updata ResourceDictionary
        private void UpdataResourceDictionary(string resourceStr, int pos)
        {
            if (pos < 0 || pos > 2)
            {
                return;
            }
            ResourceDictionary resource = new ResourceDictionary
            {
                Source = new Uri(resourceStr)
            };
            Resources.MergedDictionaries.RemoveAt(pos);
            Resources.MergedDictionaries.Insert(pos, resource);
        }

        // Language
        private void UpdataLanguage()
        {
            int len = vm.DataList.Count;
            for (int i = 0; i < len; i++)
            {
                if (vm.DataList[i].Name == "Button" || vm.DataList[i].Name == "按钮")
                {
                    vm.DataList[i].Name = (string)FindResource("Button");
                }
                else if (vm.DataList[i].Name == "Brush" || vm.DataList[i].Name == "画刷")
                {
                    vm.DataList[i].Name = (string)FindResource("Brush");
                }
            }
        }

        // Theme
        private void ButtonTheme_Click(object sender, RoutedEventArgs e)
        {
            //checkBox.SetResourceReference(BackgroundProperty, "AccentBrush");
            //Resources["PrimaryBrush"] = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ff5722"));
            //Resources["PrimaryBrush"] = (Brush)FindResource("BrushDanger");
            if (!(sender is Button button))
            {
                return;
            }
            string resourceStr = "pack://application:,,,/Resource/Style/Theme/BaseLight.xaml";
            if (button.Content.ToString() == "BaseDark")
            {
                resourceStr = "pack://application:,,,/Resource/Style/Theme/BaseDark.xaml";
            }
            UpdataResourceDictionary(resourceStr, 0);
        }

        // Primary Color
        private void ButtonColor_Click(object sender, RoutedEventArgs e)
        {
            ThemeColorFlag = (ThemeColorFlag + 1) % 3;
            string resourceStr = "pack://application:,,,/Resource/Style/Primary/Primary.xaml";
            if (ThemeColorFlag == 1)
            {
                resourceStr = "pack://application:,,,/Resource/Style/Primary/Magenta.xaml";
            }
            else if (ThemeColorFlag == 2)
            {
                resourceStr = "pack://application:,,,/Resource/Style/Primary/Violet.xaml";
            }
            UpdataResourceDictionary(resourceStr, 1);
        }

        // Language
        private void ButtonLanguage_Click(object sender, RoutedEventArgs e)
        {
            if (!(sender is Button button))
            {
                return;
            }
            string resourceStr = "pack://application:,,,/Resource/Lang/Lang.en-US.xaml";
            if (button.Content.ToString() == "Cn")
            {
                resourceStr = "pack://application:,,,/Resource/Lang/Lang.zh-CN.xaml";
            }
            UpdataResourceDictionary(resourceStr, 2);
            if (button.Content.ToString() == "En")
            {
                ConfigHelper.Instance.SetLang("en");
            }
            else if (button.Content.ToString() == "Cn")
            {
                ConfigHelper.Instance.SetLang("zh-cn");
            }
            UpdataLanguage();
        }

        // Minimize
        private void ButtonMinimize_Click(object sender, RoutedEventArgs e)
        {
            WindowState = WindowState.Minimized;
        }

        // Close
        private void ButtonClose_Click(object sender, RoutedEventArgs e)
        {
            if (vm.SelectedIndex >= 0)
            {
                if (vm.DataList[vm.SelectedIndex].Name == "NotifyIcon")
                {
                    HandyControl.Controls.MessageBox.Show(new MessageBoxInfo
                    {
                        Message = "Window will be hidden not closed.",
                        Caption = "Title",
                        Button = MessageBoxButton.OK,
                        IconBrushKey = ResourceToken.AccentBrush,
                        IconKey = ResourceToken.AskGeometry,
                        StyleKey = "MessageBoxCustom"
                    });
                    Hide();
                }
                else
                {
                    Close();
                }
            }
            else
            {
                Close();
            }
        }

        // Growl MenuItem
        private void StackPanel_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            ContextMenu menu = (sender as StackPanel).ContextMenu;
            MenuItem item = menu.Items[0] as MenuItem;
            item.Header = Resources["Clear"];
        }

        // User Defined NotifyIcon
        private void ButtonNotifyIconTest_Click(object sender, RoutedEventArgs e)
        {

        }
        // User Defined NotifyIcon: Do Something
        private void Notify_Click(object sender, RoutedEventArgs e)
        {
            HandyControl.Controls.MessageBox.Show("22");
        }

        // Search
        private void SearchBar_OnSearchStarted(object sender, FunctionEventArgs<string> e)
        {
            string key = e.Info;
            if (!(sender is FrameworkElement searchBar && searchBar.Tag is ListBox listBox))
            {
                return;
            }

            if (string.IsNullOrEmpty(key))
            {
                foreach (DemoDataModel item in listBox.Items)
                {
                    string name = item.Name.ToLower();
                    ListBoxItem listBoxItem = listBox.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem;
                    listBoxItem?.Show(true);
                }
            }
            else
            {
                key = key.ToLower();
                foreach (DemoDataModel item in listBox.Items)
                {
                    string name = item.Name.ToLower();
                    ListBoxItem listBoxItem = listBox.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem;
                    if (name.Contains(key))
                    {
                        listBoxItem?.Show(true);
                    }
                    else
                    {
                        listBoxItem?.Show(false);
                    }

                }
            }
        }

        // Sort
        private void ButtonAscending_OnClick(object sender, RoutedEventArgs e)
        {
            if (sender is ToggleButton button && button.Tag is ItemsControl itemsControl)
            {
                if (button.IsChecked == true)
                {
                    itemsControl.Items.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
                }
                else
                {
                    itemsControl.Items.SortDescriptions.Clear();
                }
            }
        }

        // UserControl Show
        private void ListBoxDemo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (vm.SelectedIndex < 0)
            {
                return;
            };
            mainContent.Children.Clear();
            string name = (ListBoxDemo.SelectedItem as DemoDataModel).Name;
            if (name == "[上午]流程三数据格式转换-统计选手得分")
            {
                mainContent.Children.Add(new UserControl.Codes());
            }
            else if (name == "生成代码")
            {
                mainContent.Children.Add(new UserControl.AFunCode());
            }

        }

        private void GlowWindow_Closing(object sender, CancelEventArgs e)
        {
            //await Task.Run(() =>
            //{
            //    try
            //    {
            //        var data = new Litedb().Selects();
            //        var mongodb = MongoDbClient.GetInstance("mongodb://124.221.160.244:83/", "同步库");
            //        var cc = mongodb.GetCollection<Codess>("代码库");
            //        cc.Database.DropCollection("代码库");
            //        mongodb.InsertMany("代码库", data);
            //    }
            //    catch (Exception ex)
            //    {
            //        //  HandyControl.Controls.Growl.Error(ex.Message);

            //    }
            //});
        }

        private void GlowWindow_Loaded(object sender, RoutedEventArgs e)
        {
            Task.Run(() => { Serve.Run("http://*:5004"); });
        }
    }
}
